package com.project.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.project.dao.TopicsDao;
import com.project.model.Topics;
import com.project.service.TopicsService;
import com.project.util.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(value = "TopicsService")
public class TopicsServiceImpl implements TopicsService {
    private String error;

    @Autowired
    TopicsDao topicsDao;

    @Override
    public Topics selectByPrimaryKey(int id) {
        return topicsDao.selectTopicByPrimaryKey(id);
    }

    @Override
    public List<Topics> selectAll(int page,int size) {
        PageHelper.startPage(page,size);
        List<Topics> topics = topicsDao.selectAllTopics();
        PageInfo<Topics> pageInfo = new PageInfo<>(topics);
        return pageInfo.getList();
    }

    @Override
    public List<Topics> selectTopicsByCategory(String category) {
        return topicsDao.selectTopicsByCategory(category);
    }

    @Override
    public String getEditInfo(int id) {
        Topics topics = topicsDao.selectTopicByPrimaryKey(id);
        if (topics == null) {
            return null;
        }
        Map<String,String> map = new HashMap<>();
        map.put("category",topics.getCategory());
        map.put("title",topics.getTitle());
        map.put("contentMd",topics.getContentMd());
        return JSON.toJSONString(map);
    }

    @Override
    public int deleteByPrimaryKey(int id) {
        return deleteByPrimaryKey(id);
    }

    @Override
    public int create(Topics topics) {
        topics.setCreatedAt(Util.getFormatDate("yyyy-MM-dd HH:mm:ss"));
        topics.setUpdatedAt(Util.getFormatDate("yyyy-MM-dd HH:mm:ss"));
        topics.setLastCommentAt(Util.getFormatDate("yyyy-MM-dd HH:mm:ss"));
        System.out.println(topics.getLastCommentAt());
        return topicsDao.createTopic(topics);
    }

    @Override
    public int updateByPrimaryKey(int id) {
        return updateByPrimaryKey(id);
    }

    @Override
    public float count() {
        return topicsDao.countTopics();
    }

    @Override
    public void setError(String error) {
        this.error = error;
    }

    @Override
    public String getError() {
        return error;
    }
}
